package com.briup.pts.web.controller;

import com.briup.pts.config.auth.TokenMap;
import com.briup.pts.config.auth.UserDetails;
import com.briup.pts.config.response.Result;
import com.briup.pts.domain.bean.Account;
import com.briup.pts.domain.dto.LoginUser;
import com.briup.pts.service.AccountService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Tag(name = "认证模块")
@Slf4j
@RequiredArgsConstructor
@RestController
public class AuthController {

    private final AccountService service;

    @Operation(summary = "登录接口", parameters = {
            @Parameter(name = "username", required = true),
            @Parameter(name = "password", required = true)
    })
    @PostMapping("/login")
    public Result<?> login(@Validated LoginUser user) {
        log.debug("当前登录的用户为:{}", user);
        // 登录校验
        Map<String, String> map = service.login(user);
        return Result.success(map)
                .apply("登录成功");
    }

    @Operation(summary = "退出登录")
    @GetMapping("/logout")
    public Result<?> logout() {
        // 退出登录需要将tokenMap中的数据删除后，在进行响应
        String username = UserDetails.username();
        TokenMap.remove(username);
        // 只需要给前端一个成功的响应即可
        return Result.success();
    }

    @Operation(summary = "获取当前登录用户的信息")
    @GetMapping("/me")
    public Result<Account> me() {
        Account account = UserDetails.currentUser();
        // 密码置空
        account.setPassword("*********");
        return Result.success(account)
                .apply("获取成功");
    }
}
